import axios from "axios";
import {ElMessage} from "element-plus";
import {refreshToken} from "@/store/modules/user";
import {getToken, removeToken} from '@/utils/cookies'
import {useStore} from '@/store'
import {useRouter} from 'vue-router';
import {logger} from "html2canvas/dist/types/core/__mocks__/logger";
import {useApiStore} from '@/stores/modules/apiStore/apiStore'

import {pinia} from '@/stores/index';
import {configData} from "@/utils/common";

const apiStore = useApiStore(pinia);


const router = useRouter()
const request = axios.create()

request.cancelToken = axios.CancelToken


// TODO 与后端约定一个通用的返回数据格式
interface ApiResponse {
  success: boolean;
  code: number;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  data: any;
  msg: string;
}

// request interceptor
request.interceptors.request.use(config => {
  config.url = window.apiObj.APP_API_PREFIX + config.url
  // config.url = window.apiObj.APP_API_ORIGIN + window.apiObj.APP_API_PREFIX + config.url
  console.log(config)
  if (!config.headers) {
    config.headers = {}

  }
  // TODO 请求头中自动添加token
  if (!config.headers.Authorization) {
    config.headers.Authorization = useStore().state.user.token;

  }

  config.headers.lang = useStore().state?.user?.lang ? useStore().state.user.lang : 'zh'

  apiStore.apiLoading = true
  return config
  // })

}, error => {
  apiStore.apiLoading = false
  return Promise.reject(error)
})

let refreshing=false;// 正在刷新标识，避免重复刷新
let waitQueue: any[] = []; // 请求等待队列

// response interceptor
request.interceptors.response.use(response => {
  const apiRes: ApiResponse = response.data
  // console.log(response)
  apiStore.apiLoading = false
  if (response.status !== 200 && response.status !== 201) {
    return Promise.reject(response)
  } else if (apiRes.code === 4001) {
    // refresh_token也过期，直接跳转登录页面重新登录
    removeToken()
    ElMessage.error('认证过期请重新登陆')
    // router.push({
    //   path: '/setting/dataCollection',
    // });
    // window.location.reload();
  }else if (apiRes.code === 400) {
    ElMessage.error(response.data.msg)
    return Promise.reject(response.data)

  } else if (apiRes.code === 401) {
    // removeToken()
    // console.log(getToken())
    //刷新toaken
    const config:any = response.config
    if (!refreshing) {
      refreshing = true
      // const refreshToken = getRefreshToken()
      return refreshToken().then((token:any) => {
        config.headers['Authorization'] = token;
        config.baseURL = window.apiObj.APP_API_PREFIX // 请求重试时，url已包含baseURL
        waitQueue.forEach(callback => callback(token)) // 已刷新token，所有队列中的请求重试
        waitQueue = []
        return request(config)
      }).catch(() => {
        // refresh_token也过期，直接跳转登录页面重新登录
        removeToken()
        // resetRouter()

        // location.reload();
      }).finally(() => {
        refreshing = false
      })
    }
  } else {
    const apiRes: ApiResponse = response.data
    // console.log(response);

    if (response.statusText=="OK"){
      return response.data
    }else
    if (apiRes.success) {
      // 只将data部分返回给业务逻辑
      return response.data
    } else {
      ElMessage.error(apiRes.msg)
      return Promise.reject(apiRes.data)
    }
  }
}, error => {
  console.log(error)
  if(error&&error.code!="ERR_CANCELED"){
    ElMessage.error('请求失败')
  }
  apiStore.apiLoading = false
  return Promise.reject(error)
})

/**
 * @description: 请求头
 * @param { AxiosRequestHeaders } data  请求头参数
 */
export type  AxiosRequestHeaders={ [x:string]:number|string|boolean}
export const requestHeaders=(data:AxiosRequestHeaders={}):AxiosRequestHeaders=>{
  let headers={
    ...data,
  }
  headers.Authorization = useStore().state.user.token;
  return headers
}

export default request
